/*
 * Copyright (C) 2007-2012 Geometer Plus <contact@geometerplus.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

package org.geometerplus.fbreader.fbreader;

import android.os.Message;

import com.example.administrator.fangbook.appliction.HtlApplication;
import com.example.administrator.fangbook.read.ReadActivity;

import org.geometerplus.fbreader.Paths;
import org.geometerplus.fbreader.book.Book;
import org.geometerplus.fbreader.book.Bookmark;
import org.geometerplus.fbreader.book.M17kPlainTxtBook;
import org.geometerplus.fbreader.book.MTxtBook;
import org.geometerplus.fbreader.book.ReadBook;
import org.geometerplus.fbreader.bookmodel.BookModel;
import org.geometerplus.fbreader.bookmodel.TOCTree;
import org.geometerplus.fbreader.fbreader.options.MiscOptions;
import org.geometerplus.fbreader.formats.BookReadingException;
import org.geometerplus.fbreader.formats.FormatPlugin;
import org.geometerplus.zlibrary.core.application.ZLApplication;
import org.geometerplus.zlibrary.core.application.ZLKeyBindings;
import org.geometerplus.zlibrary.core.filesystem.ZL17KPlainTxtFile;
import org.geometerplus.zlibrary.core.filesystem.ZLFile;
import org.geometerplus.zlibrary.core.filesystem.ZLTxtFile;
import org.geometerplus.zlibrary.core.library.ZLibrary;
import org.geometerplus.zlibrary.core.options.ZLBooleanOption;
import org.geometerplus.zlibrary.core.options.ZLColorOption;
import org.geometerplus.zlibrary.core.options.ZLEnumOption;
import org.geometerplus.zlibrary.core.options.ZLIntegerRangeOption;
import org.geometerplus.zlibrary.core.options.ZLStringOption;
import org.geometerplus.zlibrary.core.resources.ZLResource;
import org.geometerplus.zlibrary.core.sqliteconfig.ZLSQLiteConfig;
import org.geometerplus.zlibrary.core.util.ZLColor;
import org.geometerplus.zlibrary.text.model.ZLTextModel;
import org.geometerplus.zlibrary.text.view.ZLTextWordCursor;
import org.geometerplus.zlibrary.ui.android.image.ZLAndroidImageManager;
import org.geometerplus.zlibrary.ui.android.library.ZLAndroidLibrary;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public final class FBReaderApp extends ZLApplication {

//    /**
//     * 单词挖掘行动
//     * 无行动、选择单一词、开始选择、打开字典
//     */
//    public enum WordTappingAction {
//        doNothing, selectSingleWord, startSelecting, openDictionary
//    }
//
//    /**
//     * 是否允许屏幕亮度调整
//     */
//    public final ZLBooleanOption AllowScreenBrightnessAdjustmentOption =
//            new ZLBooleanOption("LookNFeel", "AllowScreenBrightnessAdjustment", false);
//    /**
//     * 文本搜索模式
//     */
//    public final ZLStringOption TextSearchPatternOption =
//            new ZLStringOption("TextSearch", "Pattern", "");
//    /**
//     * 使用单独绑定
//     */
//    public final ZLBooleanOption UseSeparateBindingsOption =
//            new ZLBooleanOption("KeysOptions", "UseSeparateBindings", false);
//
//    /**
//     * 使用双击选项
//     */
//    public final ZLBooleanOption EnableDoubleTapOption =
//            new ZLBooleanOption("Options", "EnableDoubleTap", false);
//    /**
//     * 导航所有单词选项
//     */
//    public final ZLBooleanOption NavigateAllWordsOption =
//            new ZLBooleanOption("Options", "NavigateAllWords", false);
//
//    public final MiscOptions MiscOptions = new MiscOptions();
//
//
//    public final ZLEnumOption<WordTappingAction> WordTappingActionOption =
//            new ZLEnumOption<WordTappingAction>("Options", "WordTappingAction", WordTappingAction.startSelecting);
//
//    public final ZLColorOption ImageViewBackgroundOption =
//            new ZLColorOption("Colors", "ImageViewBackground", new ZLColor(255, 255, 255));
//
//    public enum ImageTappingAction {
//        doNothing, selectImage, openImageView
//    }
//
//    public final ZLEnumOption<ImageTappingAction> ImageTappingActionOption =
//            new ZLEnumOption<ImageTappingAction>("Options", "ImageTappingAction", ImageTappingAction.openImageView);
//
//
//    private final int myDpi = ZLibrary.Instance().getDisplayDPI();
//    public final ZLIntegerRangeOption LeftMarginOption =
//            new ZLIntegerRangeOption("Options", "LeftMargin", 0, 50, myDpi / 10 + 40);
//    public final ZLIntegerRangeOption RightMarginOption =
//            new ZLIntegerRangeOption("Options", "RightMargin", 0, 50, myDpi / 10 + 40);
//    public final ZLIntegerRangeOption TopMarginOption =
//            new ZLIntegerRangeOption("Options", "TopMargin", 0, 90, 40);
//    public final ZLIntegerRangeOption BottomMarginOption =
//            new ZLIntegerRangeOption("Options", "BottomMargin", 0, 60, 30);
//
//    public final ZLIntegerRangeOption ScrollbarTypeOption =
//            new ZLIntegerRangeOption("Options", "ScrollbarType", 0, 3, FBView.SCROLLBAR_SHOW_AS_FOOTER);
//    public final ZLIntegerRangeOption FooterHeightOption =
//            new ZLIntegerRangeOption("Options", "FooterHeight", 8, 20, 9);
//    public final ZLBooleanOption FooterShowTOCMarksOption =
//            new ZLBooleanOption("Options", "FooterShowTOCMarks", true);
//    public final ZLBooleanOption FooterShowClockOption =
//            new ZLBooleanOption("Options", "ShowClockInFooter", true);
//    public final ZLBooleanOption FooterShowBatteryOption =
//            new ZLBooleanOption("Options", "ShowBatteryInFooter", true);
//    public final ZLBooleanOption FooterShowProgressOption =
//            new ZLBooleanOption("Options", "ShowProgressInFooter", true);
//
//
//    final ZLStringOption ColorProfileOption =
//            new ZLStringOption("Options", "ColorProfile", ColorProfile.DAY);
//
//    public final ZLBooleanOption ShowPreviousBookInCancelMenuOption =
//            new ZLBooleanOption("CancelMenu", "previousBook", false);
//    public final ZLBooleanOption ShowPositionsInCancelMenuOption =
//            new ZLBooleanOption("CancelMenu", "positions", true);
//
//    public final ZLBooleanOption IsAutoPayVIPChapter =
//            new ZLBooleanOption("ReadSetting", "IsAutoPayVIPChapter", false);
//    private final ZLKeyBindings myBindings = new ZLKeyBindings("Keys");
//
//    public final ZLStringOption FooterFontOption =
//            new ZLStringOption("Options", "FooterFont", "Droid Sans");

    public final FBView BookTextView;

    public BookModel Model;

    public FBReaderApp(ReadActivity activity) {
        super(activity, Paths.systemInfo(HtlApplication.getApplication()));
//        ZLSQLiteConfig.Instance();
//        ZLAndroidLibrary.Instance();
//        new ZLAndroidImageManager();
//        myWindow = new ZLAndroidApplicationWindow(this);

//        addAction(ActionCode.INCREASE_FONT, new ChangeFontSizeAction(this, +2));
//        addAction(ActionCode.DECREASE_FONT, new ChangeFontSizeAction(this, -2));
//
//        addAction(ActionCode.FIND_NEXT, new FindNextAction(this));
//        addAction(ActionCode.FIND_PREVIOUS, new FindPreviousAction(this));
//        addAction(ActionCode.CLEAR_FIND_RESULTS, new ClearFindResultsAction(this));
//
//        addAction(ActionCode.SELECTION_CLEAR, new SelectionClearAction(this));
//
//        addAction(ActionCode.TURN_PAGE_FORWARD, new TurnPageAction(this, true));
//        addAction(ActionCode.TURN_PAGE_BACK, new TurnPageAction(this, false));
//
//        addAction(ActionCode.MOVE_CURSOR_UP, new MoveCursorAction(this, FBView.Direction.up));
//        addAction(ActionCode.MOVE_CURSOR_DOWN, new MoveCursorAction(this, FBView.Direction.down));
//        addAction(ActionCode.MOVE_CURSOR_LEFT, new MoveCursorAction(this, FBView.Direction.rightToLeft));
//        addAction(ActionCode.MOVE_CURSOR_RIGHT, new MoveCursorAction(this, FBView.Direction.leftToRight));
//
//        addAction(ActionCode.VOLUME_KEY_SCROLL_FORWARD, new VolumeKeyTurnPageAction(this, true));
//        addAction(ActionCode.VOLUME_KEY_SCROLL_BACK, new VolumeKeyTurnPageAction(this, false));
//
//        addAction(ActionCode.SWITCH_TO_DAY_PROFILE, new SwitchProfileAction(this, ColorProfile.DAY));
//        addAction(ActionCode.SWITCH_TO_NIGHT_PROFILE, new SwitchProfileAction(this, ColorProfile.NIGHT));
//
//        addAction(ActionCode.EXIT, new ExitAction(this));
//
//        addAction(ActionCode.SHOW_OR_HIDE_READ_MENU, new ShowOrHideReadMenuAction(this));
//
//        addAction(ActionCode.READ_REFRESH_ACTION, new ReadRefreshReadAction(this));
//        addAction(ActionCode.READ_BUY_ACTION, new ReadRefreshReadAction(this));
//        addAction(ActionCode.READ_PRE_ACTION, new ReadPreAction(this));
//        addAction(ActionCode.READ_BY_ACTION, new ReadBuyAction(this));
//        addAction(ActionCode.READ_OPEN_VIP_ACTION, new ReadOpenVIPAction(this));
//        addAction(ActionCode.READ_SETTING_ACTION, new ReadOpenSettingsAction(this));
        myView = BookTextView = new FBView(this);
    }

    public synchronized void setBookModel(BookModel model) {
        Model = model;
    }


//    private ColorProfile myColorProfile;
//
//    public ColorProfile getColorProfile() {
//        if (myColorProfile == null) {
//            myColorProfile = ColorProfile.get(getColorProfileName());
//        }
//        return myColorProfile;
//    }
//
//    public String getColorProfileName() {
//        return ColorProfileOption.getValue();
//    }
//
//    public void setColorProfileName(String name) {
//        ColorProfileOption.setValue(name);
//        myColorProfile = null;
//    }
//
//    public ZLKeyBindings keyBindings() {
//        return myBindings;
//    }
//
//    public FBView getTextView() {
//        if (getCurrentView() != null) {
//            return (FBView) getCurrentView();
//        }
//        return null;
//    }
//
//
//    public void clearTextCaches() {
//        BookTextView.clearCaches();
//    }
//
//    public ZLTextWordCursor getCurReadCursor() {
//        if (BookTextView != null) {
//            return BookTextView.getStartCursor();
//        }
//        return null;
//    }
//
//    public void gotoBookmark(Bookmark bookmark) {
//        addInvisibleBookmark();
//        final String modelId = bookmark.ModelId;
//        if (modelId == null) {
//            BookTextView.gotoPosition(bookmark);
//            setView(BookTextView);
//        } else {
////			FootnoteView.setModel(Model.getFootnoteModel(modelId));
////			FootnoteView.gotoPosition(bookmark);
////			setView(FootnoteView);
//        }
//        getViewWidget().repaint();
//    }
//
//    public void showBookTextView() {
//        setView(BookTextView);
//    }

//    public static ReadBook createBookForFile(ZLFile file, FormatPlugin plugin) throws BookReadingException {
//
//        if (file == null) {
//            return null;
//        }
//        ReadBook book = ReadBook.getByFile(file, plugin);
//        if (book != null) {
//            book.insertIntoBookList();
//            return book;
//        }
//        if (file.isArchive()) {
//            for (ZLFile child : file.children()) {
//                book = ReadBook.getByFile(child, plugin);
//                if (book != null) {
//                    book.insertIntoBookList();
//                    return book;
//                }
//            }
//        }
//        return null;
//    }
//
//
//    private void saveBookLastReadInfo() {
//
//
//        if (Model == null || Model.Book == null || Model.Book.File == null || Model.Book.File.getShelfBook() == null) {
//            return;
//        }
//        ShelfItemBook itemBook = Model.Book.File.getShelfBook();
//
//        boolean isExist = false;
//        try {
//            ShelfItemBook book = GlobalApp.getInstance().getDataHelper().getShelfBookDao().queryForId(itemBook.getBookId());
//            isExist = book != null;
//            if (isExist) {
//                itemBook = book;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        itemBook.setLastReadDate(System.currentTimeMillis());
//        int readPercent = getReadPercent(itemBook.getBookType());
//        if (isExist) {
//            itemBook.setReadPercent(readPercent);
//            itemBook.setNewChapterCount(0);
//            BookshelfManager.getInstance().updBookReadDate(itemBook);
//        }
//        AppUtils.saveRecentBook(itemBook.getBookId(), readPercent);
//
//        final ShelfItemBook shelfBook = itemBook;
//        if (shelfBook != null && shelfBook.getBookType() == BookType.Type_ChineseAll) {
//            new Thread(new Runnable() {
//
//                @Override
//                public void run() {
//                    // TODO Auto-generated method stub
//
//                    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                    String startTime = sd.format(new Date(startReadTime));
//                    String endTime = sd.format(new Date());
////                    try {
////                        Log.d("REPORT", "汇报阅读动作结束1：" + UrlManager.getReadReportReadTimeUrl(shelfBook.getBookId(), URLEncoder.encode(startTime), URLEncoder.encode(endTime)));
////                        ConnectUtil.get(UrlManager.getReadReportReadTimeUrl(shelfBook.getBookId(), URLEncoder.encode(startTime), URLEncoder.encode(endTime)));
////                        Log.d("REPORT", "汇报阅读动作结束：" + UrlManager.getReadReportReadTimeUrl(shelfBook.getBookId(), URLEncoder.encode(startTime), URLEncoder.encode(endTime)));
////                    } catch (ErrorMsgException e) {
////                        // TODO Auto-generated catch block
////                        e.printStackTrace();
////                    } catch (IOException e) {
////                        // TODO Auto-generated catch block
////                        e.printStackTrace();
////                    }
//                }
//            }).start();
//        }
//    }
//
//    public int getReadPercent(BookType bookType) {
//        int readPercent = 0;
//        if (bookType == BookType.Type_Epub) {
//            ZLTextModel bookModel = BookTextView.getModel();
//            if (bookModel != null) {
//                int totalParagrahIndex = BookTextView.getModel().getParagraphsNumber();
//                totalParagrahIndex = totalParagrahIndex <= 0 ? 1 : totalParagrahIndex;
//                readPercent = (int) (getTextView().getEndCursor().getParagraphIndex() * 10000f / totalParagrahIndex);
//            }
//        } else if (existFile() && Model.Book.File instanceof ZL17KPlainTxtFile) {
//
//            M17kPlainTxtBook txtBook = (M17kPlainTxtBook) Model.Book;
//            if (txtBook.getReader() != null) {
//                PagePosition pagePosition = getTextView().pagePosition();
//                readPercent = (int) (txtBook.getReader().getReadPercentF() * 100 + pagePosition.Current * 100f / pagePosition.Total);
//            }
//
//        } else if (existFile() && Model.Book.File instanceof ZLTxtFile) {
//
//            MTxtBook txtBook = (MTxtBook) Model.Book;
//
//            PagePosition pagePosition = getTextView().pagePosition();
//
//            readPercent = (int) (txtBook.getReader().getReadPercentF() * 100 + pagePosition.Current * 100f / pagePosition.Total);
//        }
//        return readPercent;
//    }
//
//    private boolean existFile() {
//        return Model != null && Model.Book != null && Model.Book.File != null;
//    }

//    @Override
//    public void onWindowClosing() {
//        if (Model != null && BookTextView != null && Model.Book != null) {
////			if (Model.Book.File instanceof ZL17KPlainTxtFile && BookTextView.isShowNoNetTipState()) {
////				BookTextView.destroyChapterTipInfo();
////				((M17kPlainTxtBook) Model.Book).getReader().gotoLastChatper();
////				if(FBReaderApp.Instance().getViewWidget() != null){
////					FBReaderApp.Instance().getViewWidget().repaint();
////				}
////			}
//            Model.Book.storePosition(BookTextView.getStartCursor());
//            saveBookLastReadInfo();
//            Message msg = Message.obtain();
//            msg.what = MessageCenter.MSG_RECENT_BOOK_UPDATE;
//            MessageCenter.broadcast(msg);
//        }
//    }

	/*@Override
    public void onDestroy(){
		super.onDestroy();
		Model = null;
	}*/

//    enum CancelActionType {
//        previousBook,
//        returnTo,
//        close
//    }
//
//    public static class CancelActionDescription {
//        final CancelActionType Type;
//        public final String Title;
//        public final String Summary;
//
//        CancelActionDescription(CancelActionType type, String summary) {
//            final ZLResource resource = ZLResource.resource("cancelMenu");
//            Type = type;
//            Title = resource.getResource(type.toString()).getValue();
//            Summary = summary;
//        }
//    }
//
//    private static class BookmarkDescription extends CancelActionDescription {
//        final org.geometerplus.fbreader.book.Bookmark Bookmark;
//
//        BookmarkDescription(org.geometerplus.fbreader.book.Bookmark b) {
//            super(CancelActionType.returnTo, b.getText());
//            Bookmark = b;
//        }
//    }

//    private final ArrayList<CancelActionDescription> myCancelActionsList =
//            new ArrayList<CancelActionDescription>();
//
//    public List<CancelActionDescription> getCancelActionsList() {
//        myCancelActionsList.clear();
//        if (ShowPreviousBookInCancelMenuOption.getValue()) {
//            final Book previousBook = null;// Library.Instance().getPreviousBook();
//            if (previousBook != null) {
//                myCancelActionsList.add(new CancelActionDescription(
//                        CancelActionType.previousBook, previousBook.getTitle()
//                ));
//            }
//        }
//        if (ShowPositionsInCancelMenuOption.getValue()) {
//            if (Model != null && Model.Book != null) {
//                for (Bookmark bookmark : Bookmark.invisibleBookmarks(Model.Book)) {
//                    myCancelActionsList.add(new BookmarkDescription(bookmark));
//                }
//            }
//        }
//        myCancelActionsList.add(new CancelActionDescription(
//                CancelActionType.close, null
//        ));
//        return myCancelActionsList;
//    }
//
//    public void runCancelAction(int index) {
//        if (index < 0 || index >= myCancelActionsList.size()) {
//            return;
//        }
//
//        final CancelActionDescription description = myCancelActionsList.get(index);
//        switch (description.Type) {
//            case previousBook:
//                //openBook(Library.Instance().getPreviousBook(), null, null);
//                break;
//            case returnTo: {
//                final Bookmark b = ((BookmarkDescription) description).Bookmark;
//                b.delete();
//                gotoBookmark(b);
//                break;
//            }
//            case close:
//                closeWindow();
//                break;
//        }
//    }
//
//    private synchronized void updateInvisibleBookmarksList(Bookmark b) {
//        if (Model != null && Model.Book != null && b != null) {
//            for (Bookmark bm : Bookmark.invisibleBookmarks(Model.Book)) {
//                if (b.equals(bm)) {
//                    bm.delete();
//                }
//            }
//            b.save();
//            final List<Bookmark> bookmarks = Bookmark.invisibleBookmarks(Model.Book);
//            for (int i = 3; i < bookmarks.size(); ++i) {
//                bookmarks.get(i).delete();
//            }
//        }
//    }
//
//    public void addInvisibleBookmark(ZLTextWordCursor cursor) {
//        if (cursor != null && Model != null && Model.Book != null && getTextView() == BookTextView) {
//            updateInvisibleBookmarksList(new Bookmark(
//                    Model.Book,
//                    getTextView().getModel().getId(),
//                    cursor,
//                    6,
//                    false, null
//            ));
//        }
//    }

//    public void addInvisibleBookmark() {
//        if (Model.Book != null && getTextView() == BookTextView) {
//            updateInvisibleBookmarksList(addBookmark(6, false, null));
//        }
//    }
//
//    public Bookmark addBookmark() {
//        Bookmark b = addBookmark(50, true, null);
//        if (b != null && Model.Book != null && getTextView() == BookTextView) {
//            for (Bookmark bm : Bookmark.bookmarks()) {
//                if (b.equals(bm)) {
//                    bm.delete();
//                }
//            }
//            b.save();
//            return b;
//        }
//        return null;
//    }

//    public Bookmark addBookmark(String tag, String title) {
//        Bookmark b = addBookmark(50, true, title);
//
//
//        if (b != null && Model.Book != null && getTextView() == BookTextView) {
//
//            for (Bookmark bm : Bookmark.bookmarks()) {
//                if (b.equals(bm)) {
//                    bm.delete();
//                }
//            }
//            b.setTag(tag);
//            b.save();
//            return b;
//        }
//        return null;
//    }

//    public Bookmark addBookmark(int maxLength, boolean visible, String title) {
//        final FBView view = getTextView();
//        final ZLTextWordCursor cursor = view.getStartCursor();
//
//        if (cursor.isNull()) {
//            return null;
//        }
//
//        return new Bookmark(
//                Model.Book,
//                view.getModel().getId(),
//                cursor,
//                maxLength,
//                visible, title
//        );
//    }

//    public TOCTree getCurrentTOCElement() {
//        final ZLTextWordCursor cursor = BookTextView.getStartCursor();
//        if (Model == null || cursor == null) {
//            return null;
//        }
//
//        int index = cursor.getParagraphIndex();
//        if (cursor.isEndOfParagraph()) {
//            ++index;
//        }
//        TOCTree treeToSelect = null;
//        for (TOCTree tree : Model.TOCTree) {
//            final TOCTree.Reference reference = tree.getReference();
//            if (reference == null) {
//                continue;
//            }
//            if (reference.ParagraphIndex > index) {
//                break;
//            }
//            treeToSelect = tree;
//        }
//        return treeToSelect;
//    }

//    public final ZLStringOption VIPChapterFontOption =
//            new ZLStringOption("Options", "FooterFont", "Droid Sans");
}
